package cn.wwcyc.utils;

import cn.wwcyc.domain.User;
import cn.wwcyc.domain.UserVo;
import cn.wwcyc.service.UserService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

@Slf4j
@Component
public class JWTUtil {
    private static UserService staticUserService;
    @Autowired
    private UserService userService;
    @PostConstruct
    private void setStaticUserService(){
        staticUserService = userService;
    }
    /**
     * 生成token
     *
     * @param userVo
     * @return
     */
    public static String getToken(UserVo user, long time) {
        Date start = new Date();//token起始时间
        long currentTime = System.currentTimeMillis() + time;
        Date end = new Date(currentTime);//token结束时间
        String token = "";
        token = JWT.create()
                .withAudience(user.getId().toString()) //存放接收方的信息
                .withIssuedAt(start)//token开始时间
                .withExpiresAt(end)//token存活截止时间
                .sign(Algorithm.HMAC256(user.getPassword()));//加密
        return token;
    }
    //获取当前登录用户
    public static User getCurrentUser(){
        try {
            HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = req.getHeader("token");
            String userId = JWT.decode(token).getAudience().get(0);
            User user = staticUserService.getById(userId);
            return user;
        } catch(Exception e){
            return null;
        }
    }
}


